/* eslint-disable */
;(function(doc, win) {
  var ViewAdaption = function(option) {
    this.pw = option.pw / 2
    this.ph = option.ph / 2
    this.outer = doc.getElementById(option.outer)
    this.inner = doc.getElementById(option.inner)
  }

  ViewAdaption.prototype.init = function() {
    var self = this

    this._adption()

    win.addEventListener(
      'resize',
      function() {
        setTimeout(function() {
          self._adption()
        }, 33)
      },
      false
    )
  }

  // 适配
  ViewAdaption.prototype._adption = function() {
    var dw = doc.documentElement.clientWidth || doc.body.clientWidth,
      dh = doc.documentElement.clientHeight || doc.body.clientHeight

    this._changeOuterOrientation(dw, dh)
    this._changeInnerStyle(dw, dh)
  }

  // 改变outer方向
  ViewAdaption.prototype._changeOuterOrientation = function(dw, dh) {
    var isPortrait = dw < dh,
      styleOuter = ''

    if (isPortrait) {
      // orientation: portrait
      styleOuter += 'width:' + dh + 'px;'
      styleOuter += 'height:' + dw + 'px;'
      styleOuter +=
        '-webkit-transform-origin: ' + dw / 2 + 'px ' + dw / 2 + 'px;'
      styleOuter += 'transform-origin: ' + dw / 2 + 'px ' + dw / 2 + 'px;'
      styleOuter +=
        '-webkit-transform: rotate(90deg); transform: rotate(90deg);'
    } else {
      // orientation: landspace
      styleOuter += 'width:' + dw + 'px;'
      styleOuter += 'height:' + dh + 'px;'
      styleOuter += '-webkit-transform: rotate(0); transform: rotate(0);'
      styleOuter += '-webkit-transform-origin: 0 0;'
      styleOuter += 'transform-origin: 0 0;'
    }
    styleOuter +=
      'display: flex;justify-content: center;align-items: center;overflow: hidden;'

    this.outer.style.cssText = styleOuter
  }

  // 改变inner样式
  ViewAdaption.prototype._changeInnerStyle = function(dw, dh) {
    var isPortrait = dw < dh,
      pw = this.pw,
      ph = this.ph,
      styleInner = ''

    var scale

    if (isPortrait) {
      scale = Math.min(dw / pw, dh / ph)
    } else {
      scale = Math.min(dw / ph, dh / pw)
    }

    window.scale = scale


    styleInner += 'transform-origin: center;'
    styleInner += '-webkit-transform-origin: center;'
    styleInner += 'transform: scale(' + scale + ');'
    styleInner += 'position: absolute;'

    if (scale >= 1) {
      styleInner += 'width: 100%;'
      styleInner += 'Height: 100%;'
    } else {
      styleInner += 'width:' + ph + 'px;'
      styleInner += 'Height:' + pw + 'px;'
    }

    this.inner.style.cssText = styleInner

  }

  window.viewAdaption = function(option) {
    var o = new ViewAdaption(option)
    return o.init()
  }
})(document, window)
